use std::str::FromStr;

use axum_app_common::my_date_format;
use axum_app_dao::UserStatus;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use tracing::error;
use validator::Validate;

#[derive(Debug, Deserialize, Validate)]
pub struct UserQueryPageParams {
    pub username: Option<String>,
    pub display_name: Option<String>,
}

/// =======  user 创建 ========

#[derive(Debug, Deserialize, Validate)]
pub struct UserCreateParams {
    #[validate(length(min = 1, message = "用户名不得为空"))]
    pub username: String,

    #[validate(length(min = 1, message = "用户姓名不得为空"))]
    pub display_name: String,

    #[validate(length(min = 1, message = "手机号不得为空"))]
    pub mobile: String,
}

///  =====  user 查询  =====
#[derive(Debug, Deserialize, Validate)]
pub struct UserQueryParams {
    #[validate(range(min = 1, message = "id无效"))]
    pub id: u64,
}

#[derive(Debug, Serialize)]
pub struct UserQueryResponse {
    pub id: u64,
    pub userid: String,
    pub username: String,
    pub display_name: String,
    pub mobile: String,
    pub status: String,
    pub status_label: String,
    #[serde(with = "my_date_format")]
    pub create_time: DateTime<Utc>,
    #[serde(with = "my_date_format")]
    pub update_time: DateTime<Utc>,
}

impl TryFrom<axum_app_dao::entity::sys_user::Model> for UserQueryResponse {
    type Error = anyhow::Error;

    fn try_from(model: axum_app_dao::entity::sys_user::Model) -> Result<Self, Self::Error> {
        let status = model.status;
        let status_label = UserStatus::from_str(status.as_str());

        let status_label = match status_label {
            Ok(s) => s.get_message().unwrap().to_string(),
            Err(err) => {
                error!("用户状态值异常: value={:?}, message={:?}", status, err);
                "".to_string()
            }
        };

        Ok(UserQueryResponse {
            id: model.id as u64,
            userid: model.userid,
            username: model.username,
            display_name: model.display_name,
            mobile: model.mobile,
            status,
            status_label,
            create_time: model.create_time,
            update_time: model.update_time,
        })
    }
}

/// 用户更新
#[derive(Debug, Deserialize, Validate)]
pub struct UserUpdateParams {
    #[validate(length(min = 1, message = "用户ID不得为空"))]
    pub userid: String,

    pub username: Option<String>,

    pub display_name: Option<String>,

    pub mobile: Option<String>,
}

#[derive(Debug,Deserialize,Validate)]
pub struct UserStatusToggleParams {
    #[validate(length(min = 1, message = "用户ID不得为空"))]
    pub userid: String,

    #[validate(length(min = 1, message = "action不得为空"))]
    pub action: String,
}
